<template>
  <div class="course-info">
    <el-form ref="dataForm" :model="vip" :rules="rules" label-width="100px" style="padding-right: 40px">
      <el-form-item label="会员类型" prop="type" style="width: 400px">
        <el-input v-model="vip.type" />
      </el-form-item>
      <el-form-item label="课程价格" prop="price" style="width: 400px">
        <el-input v-model="vip.price" />
      </el-form-item>
      <el-form-item label="时长" prop="duration" style="width: 400px">
        <el-input v-model="vip.duration" />
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button size="small" icon="el-icon-refresh-right" @click="cancel">取 消</el-button>
      <el-button type="primary" icon="el-icon-check" size="small" @click="saveOrUpdate('dataForm')">确
        定</el-button>
    </span>
  </div>
</template>

<script>
import { pcTextArr } from 'element-china-area-data'
import Tinymce from '@/components/Tinymce'
import vipApi from '@/api/content/vip'

const defaultForm = {
  id:"",
  price: '',
  type:'',
  duration:'',
}

export default {
  components: { Tinymce },
  data() {
    return {
      dialogVisible: false,
      pcTextArr,
      vip: defaultForm,
      rules: {
        price: [
          { required: true, message: '请填写会员价格', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请填写会员名称', trigger: 'blur' }
        ],
        duration: [
          { required: true, message: '请填写会员时长', trigger: 'blur' }
        ],
      }
    }
  },
  mounted() {
    console.log(this.$route.query.id)
    if (!this.$route.query.id) {
      this.vip = defaultForm
    } else {
      this.fetchData(this.$route.query.id)
    }
  },
  methods: {
    fetchData(id) {
      vipApi.getById(id).then((response) => {
        this.vip = response.data
      })
    },
    // 添加或更新
    saveOrUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.vip.id) {
            this.save(formName)
          } else {
            this.update(formName)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 添加
    save() {
      vipApi.save(this.vip).then((response) => {
        this.$message.success(response.message || '操作成功')
        this.$router.replace('/content/vip')
      })
    },
    // 更新
    update(formName) {
      vipApi.updateById(this.vip).then((response) => {
        this.$message.success(response.message || '操作成功')
        this.$router.replace('/content/vip')
      })
    },
    // 取消
    cancel() {
      this.$router.go(-1)
    },
  }
}
</script>

<style lang="scss" scoped>
.course-info {
  margin: 30px;
  margin-top: 40px;

  .dialog-footer {
    margin-left: 40px;
    margin-bottom: 20px;
  }
}
</style>
